package day11;

import java.util.concurrent.locks.ReentrantLock;

//测试公平锁
public
class TestFair {
    static ReentrantLock lock=new ReentrantLock(true);//公平锁 默认false 非公平锁
    public void test(){
        String name=Thread.currentThread().getName();
        try {
            lock.lock();
            System.out.println(name+"获得锁");
            Thread.sleep(1000);
            System.out.println(name+"释放锁");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public static void main(String[] args) {
        TestFair testFair=new TestFair();
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                while (true){
                    testFair.test();
                }
            },"线程"+i).start();
        }
    }
}
